//
//  YZMyStocksViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/30.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMyStocksViewController.h"
#import "YZMyStocksHeaderView.h"
#import "YZMyStocksCell.h"
#import "YZMyStocksTopCell.h"
#import "YZMyStocksNoneCell.h"
#import "YZMStockInfo.h"
#import "YZMSavedStock.h"
#import "YZMyStocksService.h"
#import "YZClient.h"
#import "YZMStockRealDictModel.h"
#import "YZMStockRealModel.h"
#import "YZMStockSearchService.h"
#import <MJRefresh/MJRefresh.h>
#import "MTGuideImageView.h"

#define TOP_CELL_ROWHEIGHT   90
#define QUOTE_LIST_ROWHEIGHT 60
#define NONE_CELL_ROWHEIGHT  [UIScreen mainScreen].bounds.size.height - 64 - 49 - TOP_CELL_ROWHEIGHT

static NSString *const sYZMyStocksTopCellID = @"YZMyStocksTopCellID";
static NSString *const sYZMyStocksCellID = @"YZMyStocksCellID";
static NSString *const sYZMyStocksNoneCellID = @"YZMyStocksNoneCellID";
static NSString *const sYZMyStocksHeaderID = @"YZMyStocksHeaderID";

@interface YZMyStocksViewController()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, strong) NSMutableDictionary *realDataDict;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIView *emptyView;
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property (nonatomic, assign) BOOL unShowErrorFlag;

@end

@implementation YZMyStocksViewController

- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver: self];
    self.tableView.dataSource = nil;
    self.tableView.delegate = nil;
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.navigationItem.title = @"我的自选";
    self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithImage:@"icon_white_search" target:self action:@selector(rightBarItemPressed)];
    self.dataList = [NSMutableArray array];
    self.realDataDict = [NSMutableDictionary dictionary];
    [self createObjects];
    NSUserDefaults* data = [NSUserDefaults standardUserDefaults];
    
    if (![data objectForKey:@"WDZX"]) {
        [MTGuideImageView createImage: (iPhoneX ? @"zx2" : (iPhone6P ? @"zx1" : @"zx3"))];
        [data setObject:@"1" forKey:@"WDZX"];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.dataList removeAllObjects];
    [self.dataList addObjectsFromArray:[YZMyStocksService sharedService].stocks];
    [self.tableView reloadData];
    [self refreshView];
    [self startTimer];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self stopTimer];
}

#pragma mark -- network

- (BOOL)checkNetwork {
    
    if (kNetworkNotReachability) {
        
        if (!_unShowErrorFlag) {
            
            [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
            _unShowErrorFlag = YES;
        }
        
        return YES;
    }
    
    return NO;
}

- (void)fetchStockDetailInfo{
    
    if ([self checkNetwork]) {
        
        return;
    }
    
    NSMutableArray *array = [NSMutableArray array];
    for (YZMStockInfo *stock in self.dataList) {
        [array addObject: stock.code];
    }
    
    [array addObject:@"SH000001"];
    [array addObject:@"SZ399001"];
    [array addObject:@"SZ399006"];
    
    [YZClient qt_getRealtimeInfoWithStockCodes:array success:^(NSURLResponse *response, id responseObject) {
        
        if ([_refreshHeader isRefreshing]) {
            
            [_refreshHeader endRefreshing];
        }
        YZGeneralResultModel *topModel = responseObject;
        if(topModel.success){
            [self.realDataDict removeAllObjects];
            [self.realDataDict addEntriesFromDictionary:topModel.data];
            if (self.realDataDict) {
                 [self.tableView reloadData];
            }

        }else{
            
            [topModel showMessage];
        }
        
        _unShowErrorFlag = NO;
    } failure:^(NSError *error) {
        
        if ([_refreshHeader isRefreshing]) {
            
            [_refreshHeader endRefreshing];
        }
        
        if (!_unShowErrorFlag) {
            
            [error yz_showMessage];
        }
        _unShowErrorFlag = YES;
    }];
}


#pragma mark -- event

- (void) leftBarItemPressed{
    
    [YZMHCMInstance pushViewControllerWithName:@"customEdit" andParams:nil];
}

- (void)rightBarItemPressed{
    
    [YZMHCMInstance pushViewControllerWithName:@"customAdd" andParams:@{@"page":@"next"}];
}

- (void)downRefresh{
    
    [self fetchStockDetailInfo];
}

- (void)dataUpdateTimer: (NSTimer *)timer
{
    [self fetchStockDetailInfo];
}

- (void)startTimer
{
    if (self.timer == nil) {
        self.timer = [NSTimer timerWithTimeInterval: 5.0 target:self selector: @selector(dataUpdateTimer:) userInfo: nil repeats: YES];
        [[NSRunLoop mainRunLoop] addTimer: self.timer forMode: NSRunLoopCommonModes];
        [self.timer fire];
    }
}

- (void)stopTimer
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(section == 0){
        if (YZMSWitchOn) {
            return 1;
        }
        return 0;
    }
    
    return self.dataList.count == 0? 1: self.dataList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        YZMyStocksTopCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMyStocksTopCellID forIndexPath:indexPath];
        cell.leftRecord = self.realDataDict[@"SH000001"];
        cell.middleRecord = self.realDataDict[@"SZ399001"];
        cell.rightRecord = self.realDataDict[@"SZ399006"];
        return cell;
    }
    
    if (self.dataList.count == 0) {
        
        YZMyStocksNoneCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMyStocksNoneCellID forIndexPath:indexPath];
        __weak __typeof(&*self) weakSelf = self;
        cell.addAction = ^(){
            [weakSelf rightBarItemPressed];
        };
        return cell;
    }
    
    YZMyStocksCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMyStocksCellID forIndexPath:indexPath];
    YZMStockInfo *stock = self.dataList[indexPath.row];
    cell.record = stock;
    YZMStockRealModel *model = self.realDataDict[stock.code];
    if (model) {
        
        cell.realRecord = model;
        
    }
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = self.dataList.count;
    cell.indexCount = indexCount;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        return TOP_CELL_ROWHEIGHT;
    }
    
    if (self.dataList.count == 0) {
        
        return NONE_CELL_ROWHEIGHT;
    }
    return QUOTE_LIST_ROWHEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 14;
    }
    
    if (self.dataList.count == 0) {
        
        return 0;
    }
    return 52;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return [UIView new];
    }
    
    if (self.dataList.count == 0) {
        
        return [UIView new];
    }
    YZMyStocksHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:sYZMyStocksHeaderID];
    headerView.style = YZMStockHeaderTypeForShow;
    return headerView;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0 || self.dataList.count == 0) {
        
        return UITableViewCellEditingStyleNone;
    }
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        YZMSavedStock *stock = self.dataList[indexPath.row];
        [[YZMyStocksService sharedService] removeStockWithCode:stock.code];
        [self.tableView beginUpdates];
        [self.dataList removeObjectAtIndex: indexPath.row];
        if (self.dataList.count == 0) {
            
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
        }else{
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        [self.tableView endUpdates];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!YZMSWitchOn) {
        return;
    }
    NSInteger row = indexPath.row;
    if (row < self.dataList.count) {
        YZMSavedStock *stock = [self.dataList objectAtIndex: row];
        if (stock.code.length == 0) {
            return;
        }
        NSDictionary *param = nil;
        if (stock.name.length == 0) {
            param = @{@"stockcode": stock.code};
        }
        else
        {
            param = @{@"stockcode": stock.code, @"stockname": stock.name};
        }
        [[YZMStockSearchService sharedService] appendHistoryWithCode:stock.code];
        [YZMHCMInstance pushViewControllerWithName: @"stock" andParams: param];
    }
}

#pragma mark  -- refresh ui

- (void)refreshView{
    
    if (self.dataList.count == 0) {
        
        self.navigationItem.leftBarButtonItem = nil;
        
    }else{
        
        self.navigationItem.leftBarButtonItem = [YZMAppStyle leftBarItemWithTitle: @"编辑" target: self action: @selector(leftBarItemPressed)];
    }
}


#pragma mark -- ui

- (void)createObjects{
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self.tableView registerClass:[YZMyStocksTopCell class] forCellReuseIdentifier:sYZMyStocksTopCellID];
    [self.tableView registerClass:[YZMyStocksCell class] forCellReuseIdentifier:sYZMyStocksCellID];
    [self.tableView registerClass:[YZMyStocksHeaderView class] forHeaderFooterViewReuseIdentifier:sYZMyStocksHeaderID];
    [self.tableView registerClass:[YZMyStocksNoneCell class] forCellReuseIdentifier:sYZMyStocksNoneCellID];
    [self.view addSubview: self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    _refreshHeader.lastUpdatedTimeLabel.hidden = YES;
    _refreshHeader.stateLabel.textColor = [YZMAppStyle colorForGrayText];
    _refreshHeader.stateLabel.font = [YZMAppStyle mediumSizeFont];
    self.tableView.mj_header = _refreshHeader;
    
    [self refreshView];
}

@end
